package com.example.demo.navigation

//import com.example.chat.ChatFeatureSDK
//import com.example.contact.ContactFeatureSDK
//import com.example.discover.DiscoverFeatureSDK
import android.util.Log
import androidx.navigation.NavOptionsBuilder
import com.example.featuresdk.core.AbstractFeatureSDK
import com.example.featuresdk.navigation.INavigationController
import com.example.featuresdk.navigation.INavigationMediator

class NavigationMediator: INavigationMediator {

    companion object{
        const val TAG = "NavigationMediator"
    }

    private val _features = mutableListOf<AbstractFeatureSDK>()
    private val _routes = mutableMapOf<String, INavigationController>()

//    companion object{
//        val instance = NavigationMediator().apply {
//            register(ChatFeatureSDK())
//            register(ContactFeatureSDK())
//            register(DiscoverFeatureSDK())
//        }
//    }

    override fun back() {
        TODO("Not yet implemented")
    }

    override fun currentFeature(): AbstractFeatureSDK {
        TODO("Not yet implemented")
    }

    override fun targetFeature(): AbstractFeatureSDK {
        TODO("Not yet implemented")
    }

    override fun feature(featureKey: String): AbstractFeatureSDK? {
        return _features.firstOrNull { it.featureKey() == featureKey }
    }

    override fun register(featureSDK: AbstractFeatureSDK) {
        Log.i(TAG, "***register feature: key=${featureSDK.featureKey()}, class=${featureSDK.javaClass.canonicalName}")

        _features.add(featureSDK)

        val navigationController = featureSDK.getNavigationController()
        navigationController.getNavigationRoutes().forEach {
            _routes[it] = navigationController

            Log.i(TAG,"***register route: $it")
        }
    }

    override fun hasRoute(route: String): Boolean {
        return _routes.contains(route)
    }

    override fun navigate(route: String, vararg params: String, builder: NavOptionsBuilder.() -> Unit) {
        Log.i(TAG, "route=$route, hasRoute=${hasRoute(route)}")
        if(hasRoute(route)){
            _routes[route]?.navigate(route, *params){
                builder()
            }
        }
    }

    override fun features(): List<AbstractFeatureSDK> {
        return _features
    }

    override fun entitledFeatures(): List<AbstractFeatureSDK> {
        return _features.filter { it.userEntitled }
    }

    fun clear(){
        _features.clear()
        _routes.clear()
    }
}